<?php
//---------------------------------
// Autho: wwt
// Date: 2012-02-29 22:47:34
//---------------------------------
error_reporting(0);
class PlaylistParse
{
	function getsid() 
	{
		$t1 = "1000".(rand(0,999));
		$t2 = "1000".(rand(0,9000));
		$sid = time().$t1.$t2;
		return $sid;
	}
	
	function getkey($key1,$key2,$k)
	{
			if(empty($k) == false)
			{
				return $k;
			}
			$key = hexdec($key1);
			$key = $key ^ -1520786011;
			return $key2 . dechex($key);
	}
	
	function getstring($seed) 
	{
		$str = "";
		$source = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/\\:._-1234567890";
		$len = strlen($source);
		
		for($i=0;$i< $len;++$i)
		{
			$seed = ($seed * 211 + 30031) % 65536;
			$ptr = ($seed / 65536 * strlen($source));
			$c = substr($source,$ptr,1);
			$str .= $c;
			$source = str_replace($c, "",$source);
		}
		return $str;
	}
	
	function getfileid($fileId,$seed) 
	{
		$str = $this->getstring($seed);
		$ids = explode("*",$fileId);
		unset($ids[count($ids)-1]);
		
		$fileid = "";
		for ($i=0;$i < count($ids);++$i) 
		{
			$idx = $ids[$i];
			$fileid .= substr($str,$idx,1);
		}
		return $fileid;
	}
}

function file_data($url)
{
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
	curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
	@ $d = curl_exec($ch);
	curl_close($ch);
	
	return $d;
}

function get_all_list($vid)
{
	$format = "";
	$fileids = "";
	$len = 0;
	$url = "http://v.youku.com/player/getPlayList/VideoIDS/" . $vid;
	
	$str = file_data($url);

	$json = json_decode($str);
	$seed = $json->data[0]->seed;
	$key1 = $json->data[0]->key1;
	$key2 = $json->data[0]->key2;
	
	if (!empty($json->data[0]->streamfileids->mp4))
	{
		$fileids  = $json->data[0]->streamfileids->mp4;
		$len = count($json->data[0]->segs->mp4);
		$format = "mp4";
	}
	else //if (!empty($json->data[0]->streamfileids->flv))
	{
		$fileids  = $json->data[0]->streamfileids->flv;
		$len = count($json->data[0]->segs->flv);
		$format = "flv";
	}

	$PlaylistParse = new PlaylistParse();
	
	$fileid = $PlaylistParse->getfileid($fileids,$seed);
	$sid = $PlaylistParse->getsid();

	for ($j = 0; $j < $len;$j++)
	{
		$idx = vsprintf("%02X",$j);
		switch($format)
		{
		case "hd2":
			$k = $json->data[0]->segs->hd2[$j]->k;
			break;
			
		case "mp4":
			$k = $json->data[0]->segs->mp4[$j]->k;
			break;
			
		case "flv":
		default:
			$k = $json->data[0]->segs->flv[$j]->k;
			break;
		}
		$key = $PlaylistParse->getkey($key1,$key2,$k);
		$item = "http://f.youku.com/player/getFlvPath/sid/" . $sid ."_". $idx . "/st/" . $format . "/fileid/" . substr($fileid,0,8) . $idx . substr($fileid,10) . "?K=" . $key . "\n";
		echo $item;
	}
}

if (isset ($_GET['vid'])) 
{
	$vid = $_GET['vid'];
	get_all_list($vid);
}

?>
